package experiment.networkmodel;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class SingleServer {

	protected ServerSocket provider;
	protected Socket client;
	protected ObjectOutputStream objOut;
	protected ObjectInputStream objIn;
	private String message;

	public SingleServer() {
		try {
			provider = new ServerSocket(2013, 0, InetAddress.getLocalHost());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void run() {
		System.out.println("Listening for client: " + provider);
		try {
			client = provider.accept();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			objIn = new ObjectInputStream(client.getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			objOut = new ObjectOutputStream(client.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		do {

			try {
				message = (String) objIn.readObject();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if (message.equals("bye")) {
				try {
					objOut.writeObject("bye");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			}
			
			System.out.println("client>" + message);
			System.out.print("reply>");

		} while (!message.equals("bye"));
	}
	
	public void sendLine(){
		Scanner scan = new Scanner(System.in);
		
		try {
			objOut.writeObject(scan.nextLine());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	
	
	
	
	
	public static void main (String args[]){
		SingleServer server = new SingleServer();
		server.run();
	}

}
